package com.niiwoo.civet.account.service.local;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dao.entity.*;
import com.niiwoo.civet.account.dao.mapper.*;
import com.niiwoo.civet.account.dto.request.RebindCompanyBankCardRequestDTO;
import com.niiwoo.civet.account.dto.request.UnbindCompanyBankCardCallbackRequestDTO;
import com.niiwoo.civet.account.dto.response.RebindCompanyBankCardResponseDTO;
import com.niiwoo.civet.account.dto.response.UnbindBankCardCallbackResponseDTO;
import com.niiwoo.civet.account.enums.*;
import com.niiwoo.civet.base.constant.OrgConstant;
import com.niiwoo.civet.base.enums.CommonOrderStatusEnum;
import com.niiwoo.civet.base.enums.DelFlagEnum;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.lanmao.component.LanMaoGatewayService;
import com.niiwoo.tripod.lanmao.component.LanMaoSequence;
import com.niiwoo.tripod.lanmao.enums.BankCodeEnum;
import com.niiwoo.tripod.lanmao.request.CompanyBindBankCardExpandRequest;
import com.niiwoo.tripod.lanmao.response.LanMaoGatewayDTO;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 银行卡本地服务类
 * Created by wangjichao on 2017/11/8.
 */
@Service
@Slf4j
public class BankCardService {

    @Autowired
    private BankTypeMapper bankTypeMapper;

    @Autowired
    private BankTypeMapperExt bankTypeMapperExt;

    @Autowired
    private BankCardMapperExt bankCardMapperExt;

    @Autowired
    private BankCardRebindOrderMapperExt bankCardRebindOrderMapperExt;

    @Autowired
    private NiiwooBillMapperExt niiwooBillMapperExt;

    @Autowired
    private BankCardRebindOrderMapper bankCardRebindOrderMapper;

    @Autowired
    private BankCardRebindOrderAttachmentMapper bankCardRebindOrderAttachmentMapper;

    @Autowired
    private BankCardRebindAuditConfirmOrderMapper bankCardRebindAuditConfirmOrderMapper;

    @Autowired
    private PayChannelMapperExt payChannelMapperExt;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    private LanMaoSequence lanMaoSequence;

    @Autowired
    private UnbindBankCardOrderMapperExt unbindBankCardOrderMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private BankTypeService bankTypeService;

    @Autowired
    private LanMaoGatewayService lanMaoGatewayService;

    @Autowired
    private AccountCompanyService accountCompanyService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private BankCardService bankCardService;

    @Autowired
    private PrivacyMasks privacyMasks;

    /**
     * 获取系统支持的银行列表
     * @return
     */
    public List<BankType> getSupportBankTypeList() {
        return bankTypeMapperExt.selectSupportBankTypeList();
    }

    /**
     * 获取系统支持的银行列表（PC端展示）
     * @return
     */
    public List<BankType> getSupportBankTypeListByPC() {
        return bankTypeMapperExt.selectSupportBankTypeListByPC();
    }

    /**
     * 根据卡号前缀查询对应的银行类型（卡bin接口）
     * @return
     */
    public BankType getBankTypeByCardBinNo(String cardBinNo) {
        return bankTypeMapperExt.selectBankTypeByCardBinNo(cardBinNo);
    }

    /**
     * 通过id查询银行卡信息
     * @param id
     * @return
     */
    public BankCard getBankCardInfoById(Long id){
        return bankCardMapperExt.selectByPrimaryKey(id);
    }

    /**
     * 查询普通用户银行卡信息
     * 注：仅针对你我金融平台用户,不包括机构极速借用户银行卡
     * @param userId
     * @return
     */
    public BankCard getSimpleUserBankCard(String userId){
        return bankCardMapperExt.selectSimpleUserBankCard(userId);
    }

    /**
     * 查询机构账户银行卡信息
     * @param
     * @param accountId
     * @return
     */
    public BankCard getOrgUserBankCard(Long accountId) {
        return bankCardMapperExt.selectOrgUserBankCard(accountId);
    }

    /**
     * 查询普通用户银行卡信息
     * @param userId
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public BankCard getNewestSimpleUserBankCard(String userId){
        return this.getSimpleUserBankCard(userId);
    }


    /**
     * 获取用户银行卡
     * @param accountBase
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public BankCard loadBankCard(AccountBase accountBase){
        BankCard bankCard = null;

        if(OrgConstant.NIIWOO_ORG_ID.equals(accountBase.getOrgId())){
            //如果是你我金融账户，说明是集团账户体系，因多个账户共用一张银行卡，因此仅适用userId查询银行卡
            bankCard = this.getSimpleUserBankCard(accountBase.getUserId());
        }else{
            //如果非集团账户，银行卡会挂靠在从具体机构所开的借款户上。查询时需带上accountId
            bankCard = this.getOrgUserBankCard(accountBase.getId());
        }

        if (bankCard == null) {
            throw new BizException("ACC10012");
        }

        return bankCard;
    }


    /**
     * 查询当前用户待审批的换绑卡申请
     * @param userId
     * @return
     */
    public BankCardRebindOrder getCurrentRebindOrder(String userId){
        return bankCardRebindOrderMapperExt.selectCurrentRebindOrder(userId);
    }

    /**
     * 根据用户ID和账户ID查询当前用户待审批的换绑卡申请
     * @param userId
     * @return
     */
    public BankCardRebindOrder getCurrentRebindOrderWithAccountIds(String userId,List<Long> accountIds){
        return bankCardRebindOrderMapperExt.selectCurrentRebindOrderWithAccountIds(userId,accountIds);
    }


    /**
     * 根据ID查询银行类型
     * @param bankTypeId
     * @return
     */
    public BankType getBankTypeById(Long bankTypeId){
        return bankTypeMapper.selectByPrimaryKey(bankTypeId);
    }

    /**
     * 判断用户是否有交易流水,用于换绑卡前置检查
     * @param userId
     * @return
     */
    public NiiwooBill getExistBillForRebindCheck(String userId){
        return niiwooBillMapperExt.selectExistBillForRebindCheck(userId);
    }

    /**
     * 判断用户是否有交易流水,用于换绑卡前置检查
     *
     * @param userId
     * @return
     */
    public NiiwooBill getExistBillForRebindCheck(String userId,String orgId){
        return niiwooBillMapperExt.selectExistBillByUserIdAndOrgId(userId,orgId);
    }

    /**
     * 生成换绑卡订单
     * @param bankCardRebindOrder
     */
    @Transactional
    public void initBankCardRebindOrder(BankCardRebindOrder bankCardRebindOrder, List<BankCardRebindOrderAttachment> attachmentList){
        bankCardRebindOrderMapper.insertSelective(bankCardRebindOrder);
        if(attachmentList!=null){
            for (BankCardRebindOrderAttachment attachment : attachmentList) {
                bankCardRebindOrderAttachmentMapper.insertSelective(attachment);
            }
        }
    }

    /**
     * 根据流水号查询换绑卡订单
     * @param requestNo
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public BankCardRebindOrder getBankCardRebindOrderByRequestNoFromMaster(String requestNo){
        return bankCardRebindOrderMapperExt.selectByRequestNo(requestNo);
    }


    /**
     * 换绑卡预提交回调
     * @param rebindOrderId
     * @return
     */
    @Transactional
    public BankCardRebindAuditConfirmOrder bankCardRebindCallbackSuccess(Long rebindOrderId,BankType bankType){
        //根据主键获取排它锁避免出现间隙锁
        BankCardRebindOrder bankCardRebindOrder = bankCardRebindOrderMapperExt.selectByPrimaryKeyForUpdate(rebindOrderId);
        //如果订单状态不是处理中说明重复回调。
        if(!BankCardRebindApplyStatusEnum.INIT.getValue().equals(bankCardRebindOrder.getApplyStatus())){
            throw new BizException("ACC10017");
        }
        //回调更新银行类型以及预申请状态
        bankCardRebindOrder.setBankTypeId(bankType.getId());
        bankCardRebindOrder.setBankCode(bankType.getBankCode());
        bankCardRebindOrder.setApplyStatus(BankCardRebindApplyStatusEnum.SUBMITTED.getValue());
        //手动审核
        if(BankCardRebindAuditTypeEnum.MANUAL.getValue().equals(bankCardRebindOrder.getAuditType())){
            bankCardRebindOrder.setAuditStatus(BankCardRebindAuditStatusEnum.WAITING_APPROVE.getValue());
            bankCardRebindOrderMapper.updateByPrimaryKeySelective(bankCardRebindOrder);
            return null;
        }
        //自动审核
        else{
            //插入换绑卡审核确认订单
            BankCardRebindAuditConfirmOrder confirmOrder = new BankCardRebindAuditConfirmOrder();
            confirmOrder.setId(snowflakeIdWorker.nextId());
            confirmOrder.setRequestNo(lanMaoSequence.getRequestNo());
            confirmOrder.setRebindOrderId(bankCardRebindOrder.getId());
            confirmOrder.setAuditResult(BankCardRebindAuditStatusEnum.PASS.getValue());
            confirmOrder.setStatus(CommonOrderStatusEnum.PROCESS.getValue());
            confirmOrder.setCreateTime(new Date());
            bankCardRebindAuditConfirmOrderMapper.insertSelective(confirmOrder);
            //更新绑卡订单
            bankCardRebindOrder.setAuditStatus(BankCardRebindAuditStatusEnum.PASS.getValue());
            bankCardRebindOrderMapper.updateByPrimaryKeySelective(bankCardRebindOrder);
            return confirmOrder;
        }
    }

    @Transactional
    public void autoAuditRebindOrder(BankCardRebindOrder rebindOrder,BankCardRebindAuditConfirmOrder confirmOrder,BankType bankType){
        //更新换绑卡记录
        BankCardRebindOrder updateRebindOrder = new BankCardRebindOrder();
        updateRebindOrder.setId(rebindOrder.getId());
        updateRebindOrder.setAuditConfirmStatus(BankCardAuditConfirmStatus.CONFIRMED.getValue());
        bankCardRebindOrderMapper.updateByPrimaryKeySelective(updateRebindOrder);

        //更新换绑卡确认订单
        BankCardRebindAuditConfirmOrder updateConfirmOrder = new BankCardRebindAuditConfirmOrder();
        updateConfirmOrder.setId(confirmOrder.getId());
        updateConfirmOrder.setStatus(CommonOrderStatusEnum.SUCCESS.getValue());
        bankCardRebindAuditConfirmOrderMapper.updateByPrimaryKeySelective(updateConfirmOrder);

        //作废老卡
        BankCard oldBankCard = bankCardMapperExt.selectByPrimaryKey(rebindOrder.getOldBankCardId());
        BankCard updateOldBankCard = new BankCard();
        updateOldBankCard.setId(rebindOrder.getOldBankCardId());
        updateOldBankCard.setDelType(BankCardDelTypeEnum.REBIND.getType());
        updateOldBankCard.setDelFlag(DelFlagEnum.DELETE.getValue());
        bankCardMapperExt.updateByPrimaryKeySelective(updateOldBankCard);

        //插入新卡
        BankCard newBankCard = new BankCard();
        newBankCard.setId(snowflakeIdWorker.nextId());
        newBankCard.setUserId(rebindOrder.getUserId());
        newBankCard.setDelFlag(DelFlagEnum.UN_DELETE.getValue());
        newBankCard.setBankAccountNo(rebindOrder.getBankAccountNo());
        newBankCard.setBankCode(bankType.getBankCode());
        newBankCard.setBankTypeId(bankType.getId());
        newBankCard.setMobileNo(rebindOrder.getMobileNo());
        newBankCard.setAccountType(oldBankCard.getAccountType());
        newBankCard.setType(oldBankCard.getType());
        newBankCard.setIdCard(oldBankCard.getIdCard());
        newBankCard.setRealName(oldBankCard.getRealName());
        newBankCard.setCreateTime(new Date());
        newBankCard.setAccountId(oldBankCard.getAccountId());
        bankCardMapperExt.insertSelective(newBankCard);
    }

    @Transactional
    public void singleBindCard(AccountCompany accountCompany,BankCardRebindOrder rebindOrder,BankCardRebindAuditConfirmOrder confirmOrder,BankType bankType){
        //更新换绑卡记录
        BankCardRebindOrder updateRebindOrder = new BankCardRebindOrder();
        updateRebindOrder.setId(rebindOrder.getId());
        updateRebindOrder.setAuditConfirmStatus(BankCardAuditConfirmStatus.CONFIRMED.getValue());
        bankCardRebindOrderMapper.updateByPrimaryKeySelective(updateRebindOrder);

        //更新换绑卡确认订单
        BankCardRebindAuditConfirmOrder updateConfirmOrder = new BankCardRebindAuditConfirmOrder();
        updateConfirmOrder.setId(confirmOrder.getId());
        updateConfirmOrder.setStatus(CommonOrderStatusEnum.SUCCESS.getValue());
        bankCardRebindAuditConfirmOrderMapper.updateByPrimaryKeySelective(updateConfirmOrder);

        //插入新卡
        BankCard newBankCard = new BankCard();
        newBankCard.setId(snowflakeIdWorker.nextId());
        newBankCard.setUserId(rebindOrder.getUserId());
        newBankCard.setDelFlag(DelFlagEnum.UN_DELETE.getValue());
        newBankCard.setBankAccountNo(rebindOrder.getBankAccountNo());
        newBankCard.setBankCode(bankType.getBankCode());
        newBankCard.setBankTypeId(bankType.getId());
        newBankCard.setMobileNo(rebindOrder.getMobileNo());
        newBankCard.setAccountType(AccountTypeEnum.ENTERPRISE.getValue());
        newBankCard.setType(BankCardTypeEnum.COMPANY.getType());
        newBankCard.setIdCard(accountCompany.getLegalPersonIdCard());
        newBankCard.setRealName(accountCompany.getLegalPersonName());
        newBankCard.setCreateTime(new Date());
        newBankCard.setAccountId(accountCompany.getAccountId());
        bankCardMapperExt.insertSelective(newBankCard);
    }

    /**
     * 查询某一银行是否支持代扣
     * @param bankTypeId
     * @return
     */
    public Boolean isSupportWithhold(Long bankTypeId){
        PayChannel payChannel = payChannelMapperExt.selectIfSupportWithhold(bankTypeId);
        return payChannel != null;
    }

    /**
     * 查询支持代扣的银行列表
     * @return
     */
    public List<Long> getWithholdBankList(){
        return bankTypeMapperExt.selectWithholdBankList();
    }

    /**
     * 查询银行类型，忽略启用状态
     * @param bankCode
     * @return
     */
    public BankType getBankTypeByCodeIgnoreStatus(String bankCode){
        return bankTypeMapperExt.selectBankTypeByCodeIgnoreStatus(bankCode);
    }

    /**
     * 查询5分钟前所有预申请未提交的数据
     * @return
     */
    public List<BankCardRebindOrder> listBankCardForJob(){
        return bankCardRebindOrderMapperExt.listBankCardForJob();
    }

    /**
     * 更新银行卡换绑记录
     * @param bankCardRebindOrder
     */
    @Transactional
    public void updateBankCardRebindOrder(BankCardRebindOrder bankCardRebindOrder){
        bankCardRebindOrderMapper.updateByPrimaryKeySelective(bankCardRebindOrder);
    }

    /**
     * 更新银行卡信息
     * @param updateCard
     * @return
     */
    public boolean updateBankCard(BankCard updateCard) {
        return bankCardMapperExt.updateByPrimaryKeySelective(updateCard) > 0;
    }

    /**
     * 插入银行卡信息
     * @param updateCard
     * @return
     */
    public Boolean saveBankCard(BankCard updateCard) {
        return bankCardMapperExt.insertSelective(updateCard) > 0;
    }

    @Transactional
    public void initUnbindBankCardOrder(UnbindBankCardOrder unbindBankCardOrder,String redirectURL){
        unbindBankCardOrderMapper.insertSelective(unbindBankCardOrder);
        redisTemplate.opsForValue().set(unbindBankCardOrder.getRequestNo(), redirectURL, 15, TimeUnit.MINUTES);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public RebindCompanyBankCardResponseDTO rebindCompanyBankCardOrder(RebindCompanyBankCardRequestDTO rebindCompanyBankCardRequestDTO) {
        log.info("企业换绑银行卡,机构ID={},请求参数={}", rebindCompanyBankCardRequestDTO.getOrgId(), JSON.toJSONString(rebindCompanyBankCardRequestDTO));
        String reuqetNo = lanMaoSequence.getRequestNo();
        //1.初始化换绑卡订单;
        BankCardRebindOrder bankCardRebindOrder = new BankCardRebindOrder();
        bankCardRebindOrder.setId(snowflakeIdWorker.nextId());
        bankCardRebindOrder.setRequestNo(reuqetNo);
        bankCardRebindOrder.setUserId(rebindCompanyBankCardRequestDTO.getOrgId());

        AccountBase accountBase=accountService.loadAccountByAccountNo(rebindCompanyBankCardRequestDTO.getPlatformUserNo());
        if (accountBase == null) {
            log.error("企业换绑银行卡,机构ID={},发生异常,原因是帐户不存在.", rebindCompanyBankCardRequestDTO.getOrgId());
            throw new BizException("ACC17014");
        }

        BankType bankType = bankTypeService.getBankTypeByCode(rebindCompanyBankCardRequestDTO.getBankCode());
        if (bankType == null) {
            log.error("企业换绑银行卡,机构ID={},发生异常,原因无效的银行类型.", rebindCompanyBankCardRequestDTO.getOrgId());
            throw new BizException("ACC10013");
        }
        bankCardRebindOrder.setAccountId(accountBase.getId());
        bankCardRebindOrder.setBankTypeId(bankType.getId());
        bankCardRebindOrder.setBankCode(rebindCompanyBankCardRequestDTO.getBankCode());
        bankCardRebindOrder.setBankAccountNo(privacyMasks.encryptPrivacy(rebindCompanyBankCardRequestDTO.getBankCardNo()));
        bankCardRebindOrder.setMobileNo(rebindCompanyBankCardRequestDTO.getMobileNo());
        bankCardRebindOrder.setUserDesc("企业换绑卡");

        //查询用户旧银行卡信息
        BankCard oldBankCard = bankCardService.getOrgUserBankCard(accountBase.getId());
        bankCardRebindOrder.setOldBankCardId(oldBankCard == null ? -1 : oldBankCard.getId());
        bankCardRebindOrder.setType(BankCardRebindTypeEnum.COMPANY.getType());
        bankCardRebindOrder.setApplyStatus(BankCardRebindApplyStatusEnum.INIT.getValue());
        bankCardRebindOrder.setAuditStatus(BankCardRebindAuditStatusEnum.INIT.getValue());
        bankCardRebindOrder.setAuditType(BankCardRebindAuditTypeEnum.AUTO.getValue());
        bankCardRebindOrder.setAuditConfirmStatus(BankCardRebindAuditConfirmStatusEnum.INIT.getValue());
        Date now = new Date();
        bankCardRebindOrder.setExpiredTime(new DateTime(now).plusMinutes(15).toDate());
        bankCardRebindOrder.setCreateTime(now);

        bankCardRebindOrderMapper.insertSelective(bankCardRebindOrder);

        BankCard bankCard=getOrgUserBankCard(accountBase.getId());
        //2.存管企业换绑卡预处理;
        CompanyBindBankCardExpandRequest companyBindBankCardExpandRequest = new CompanyBindBankCardExpandRequest();
        companyBindBankCardExpandRequest.setRequestNo(reuqetNo);
        companyBindBankCardExpandRequest.setNiiwooRedirectUrl(rebindCompanyBankCardRequestDTO.getRedirectURL());
        companyBindBankCardExpandRequest.setPlatformUserNo(rebindCompanyBankCardRequestDTO.getPlatformUserNo());
        companyBindBankCardExpandRequest.setBankcardNo(rebindCompanyBankCardRequestDTO.getBankCardNo());
        companyBindBankCardExpandRequest.setBankcode(BankCodeEnum.enumOf(rebindCompanyBankCardRequestDTO.getBankCode()));
        if(bankCard==null){
            companyBindBankCardExpandRequest.setBindType(null);
        }

        log.info("企业换绑银行卡,机构ID={},存管请求参数={}", rebindCompanyBankCardRequestDTO.getOrgId(), JSON.toJSONString(companyBindBankCardExpandRequest));
        LanMaoGatewayDTO lanMaoGatewayDTO = lanMaoGatewayService.companyBindBankCardExpand(companyBindBankCardExpandRequest);
        log.info("企业换绑银行卡,机构ID={},存管响应结果={}", rebindCompanyBankCardRequestDTO.getOrgId(), JSON.toJSONString(lanMaoGatewayDTO));

        return new RebindCompanyBankCardResponseDTO(lanMaoGatewayDTO.getAction(), lanMaoGatewayDTO.getParams());
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public UnbindBankCardCallbackResponseDTO unbindBankCardCallbackSuccess(UnbindCompanyBankCardCallbackRequestDTO unbindCompanyBankCardCallbackRequestDTO) {
        //查询解绑订单
        UnbindBankCardOrder unbindBankCardOrder = unbindBankCardOrderMapper.selectByRequestNo(unbindCompanyBankCardCallbackRequestDTO.getRequestNo());

        if (unbindBankCardOrder == null) {
            throw new BizException("ACC10042");
        }

        AccountCompany accountCompany=accountCompanyService.queryAccountCompanyByOrgId(unbindBankCardOrder.getUserId());
        if(accountCompany==null){
            throw new BizException("ACC17014");
        }

        if(!unbindBankCardOrder.getStatus().equals(UnbindBankCardStatusEnum.IN_HAND.getStatus())){
            log.info("企业解绑银行卡回调处理,请求流水号={},订单已处理完成,该请求为并发请求.", unbindCompanyBankCardCallbackRequestDTO.getRequestNo());
            return new UnbindBankCardCallbackResponseDTO(UnbindBankCardStatusEnum.SUCCESS,accountCompany.getCompanyName());
        }

        //将企业账户银行卡置为空
        accountCompanyService.resetBankCardNoAndBankCode(accountCompany.getAccountId());

        //更新解绑订单状态为成功
        updateUnbindBankCardOrder(unbindCompanyBankCardCallbackRequestDTO, unbindBankCardOrder, UnbindBankCardStatusEnum.SUCCESS.getStatus());

        AccountBase accountBase=accountService.loadAccountByAccountNo(unbindBankCardOrder.getPlatformUserNo());
        if (accountBase==null) {
            throw new BizException("ACC17014");
        }

        //查询已绑定的银行卡
        BankCard bankCard = bankCardMapperExt.selectOrgUserBankCard(accountBase.getId());

        BankCard bankCard2Update = new BankCard();
        bankCard2Update.setId(bankCard.getId());
        bankCard2Update.setDelType(BankCardDelTypeEnum.UNBIND.getType());
        bankCard2Update.setDelFlag(DelFlagEnum.DELETE.getValue());
        bankCard2Update.setUpdateTime(new Date());

        //将已绑定银行卡置为无效卡
        bankCardMapperExt.updateByPrimaryKeySelective(bankCard2Update);

        return new UnbindBankCardCallbackResponseDTO(UnbindBankCardStatusEnum.SUCCESS,accountCompany.getCompanyName());
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public UnbindBankCardCallbackResponseDTO unbindBankCardCallbackFailed(UnbindCompanyBankCardCallbackRequestDTO unbindCompanyBankCardCallbackRequestDTO) {
        //查询解绑订单
        UnbindBankCardOrder unbindBankCardOrder = unbindBankCardOrderMapper.selectByRequestNo(unbindCompanyBankCardCallbackRequestDTO.getRequestNo());
        if (unbindBankCardOrder == null) {
            throw new BizException("ACC10042");
        }

        AccountCompany accountCompany=accountCompanyService.queryAccountCompanyByOrgId(unbindBankCardOrder.getUserId());
        if(accountCompany==null){
            throw new BizException("ACC17014");
        }

        //更新解绑订单为失败
        updateUnbindBankCardOrder(unbindCompanyBankCardCallbackRequestDTO, unbindBankCardOrder, UnbindBankCardStatusEnum.FAILED.getStatus());

        return new UnbindBankCardCallbackResponseDTO(UnbindBankCardStatusEnum.FAILED,accountCompany.getCompanyName());
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    private void updateUnbindBankCardOrder(UnbindCompanyBankCardCallbackRequestDTO unbindCompanyBankCardCallbackRequestDTO, UnbindBankCardOrder unbindBankCardOrder, Byte status) {
        UnbindBankCardOrder unbindBankCardOrder2Update = new UnbindBankCardOrder();
        unbindBankCardOrder2Update.setId(unbindBankCardOrder.getId());
        unbindBankCardOrder2Update.setStatus(status);
        unbindBankCardOrder2Update.setLanmaoCode(unbindCompanyBankCardCallbackRequestDTO.getCode());
        unbindBankCardOrder2Update.setLanmaoStatus(unbindCompanyBankCardCallbackRequestDTO.getStatus());
        unbindBankCardOrder2Update.setLanmaoErrorCode(unbindCompanyBankCardCallbackRequestDTO.getErrorCode());
        unbindBankCardOrder2Update.setLanmaoErrorMsg(unbindCompanyBankCardCallbackRequestDTO.getErrorMsg());
        unbindBankCardOrder2Update.setUpdateTime(new Date());

        unbindBankCardOrderMapper.updateByPrimaryKeySelective(unbindBankCardOrder2Update);
    }

    /**
     * 查询换绑中的订单[只针对机构用户]
     * @param accountId
     */
    public List<BankCardRebindOrder> queryRebindingOrderForCompany(Long accountId){
        BankCardRebindOrderExample example = new BankCardRebindOrderExample();
        BankCardRebindOrderExample.Criteria criteria = example.createCriteria();
        criteria.andAccountIdEqualTo(accountId);
        List<Byte> auditStatusList = new ArrayList<Byte>();
        auditStatusList.add(BankCardRebindAuditStatusEnum.INIT.getValue());
        auditStatusList.add(BankCardRebindAuditStatusEnum.WAITING_APPROVE.getValue());
        criteria.andAuditStatusIn(auditStatusList);

        return bankCardRebindOrderMapperExt.selectByExample(example);
    }
}
